package com.fdb.basic.framework.redis.lock;

import org.springframework.beans.factory.annotation.Value;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * JedisCluster工厂类
 *
 * @author xiaojunhui
 */
public class JedisClusterFactory {

    private JedisCluster jedisCluster;
    @Value("${redis.maxIdle:50}")
    private int maxIdle;
    @Value("${redis.maxActive:500}")
    private int maxTotal;
    @Value("${redis.maxWaitMillis:20000}")
    private int maxWaitMillis;
    @Value("${redis.hosts}")
    private String hosts;
    @Value("${redis.password}")
    private String password;
    @Value("${redis.timeout:86400}")
    private int connectionTimeout;
    @Value("${redis.maxWait:300}")
    private int soTimeOut;
    @Value("${redis.maxAttempts:3}")
    private int maxAttempts;
    @Value("${redis.testOnBorrow:true}")
    private boolean testOnBorrow;

    public void init() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        String[] hostArry = hosts.split(",");
        Set<HostAndPort> nodes = new HashSet<>();
        if (hostArry.length > 0) {
            Arrays.stream(hostArry).forEach(p -> {
                String[] detail = p.split(":");
                nodes.add(new HostAndPort(detail[0], Integer.parseInt(detail[1])));
            });
        }
        this.jedisCluster = new JedisCluster(nodes, connectionTimeout, soTimeOut, maxAttempts, password, jedisPoolConfig);

    }

    public void destroy() {
        if (jedisCluster != null) {
            try {
                jedisCluster.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public JedisCluster getJedisCluster() {
        return jedisCluster;
    }

    public void setJedisCluster(JedisCluster jedisCluster) {
        this.jedisCluster = jedisCluster;
    }

}
